package bagu.juc.lock;

import java.util.concurrent.locks.ReentrantLock;

public class Counter {
    private int count = 0;
    private final ReentrantLock lock = new ReentrantLock();

    public void incrementNoLock() {
        try {
            Thread.sleep(1);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        count++;
    }

    // 临界区代码：统一时刻只能有一个线程对count进行访问
    // reentrantLock 上锁
    public void increment() {
        lock.lock();
        try {
            count++;
        } finally {
            lock.unlock();
        }
    }

    // synchronized实现锁，锁定当前实例对象
    public synchronized void incrementV2() {
        try {
            Thread.sleep(1);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        count++;
    }

    // 同样锁定当前实例对象
    public void incrementV3() {
        synchronized (this) {
            try {
                Thread.sleep(1);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            count++;
        }
    }


    // 获取计数
    public int getCount() {
        lock.lock();
        try {
            return count;
        } finally {
            lock.unlock();
        }
    }

}
